import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;

public class jdbcDemo2 {
    public static void main(String[] args) {

        Connection connection = null;

        PreparedStatement preparedStatement = null;

        ResultSet resultSet = null;

        try {
            //定义mysql数据源对象
            MysqlDataSource mysqlDataSource = new MysqlDataSource();
            mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/java113");
            mysqlDataSource.setUser("root");
            mysqlDataSource.setPassword("gjm041027");

            //定义jdbc对象
            DataSource dataSource = mysqlDataSource;

            //通过数据源获取数据库连接
            connection = dataSource.getConnection();

            //获取预处理SQL执行对象
            String sql = "select student_id, sn, name, mail, class_id from student";
            preparedStatement = connection.prepareStatement(sql);

            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                Long student_id = resultSet.getLong("student_id");
                String sn = resultSet.getString("sn");
                String name = resultSet.getString("name");
                String mail = resultSet.getString("mail");
                Long class_id = resultSet.getLong("class_id");
                System.out.println(MessageFormat.format("学生编号 = {0}，学号 = {1}，姓名 = {2}，邮箱 = {3}，班级编号{4}",
                        student_id, sn, name, mail, class_id));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (resultSet != null) {
                    resultSet.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            try {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
